#include <iostream>
#include <string>
#include <vector>
#include <iomanip> // 添加这一行

class RC4 {
public:
    RC4(const std::string &key) {
        keySchedule(key);
    }

    std::string encryptDecrypt(const std::string &data) {
        std::string output;
        output.resize(data.size());

        for (size_t i = 0; i < data.size(); ++i) {
            output[i] = data[i] ^ keystream();
        }
        return output;
    }

private:
    void keySchedule(const std::string &key) {
        int keyLength = key.size();
        S.resize(256);
        K.resize(256);

        // 初始化状态向量
        for (int i = 0; i < 256; ++i) {
            S[i] = i;
            K[i] = key[i % keyLength];
        }

        // 打乱状态向量
        for (int i = 0, j = 0; i < 256; ++i) {
            j = (j + S[i] + K[i]) % 256;
            std::swap(S[i], S[j]);
        }
    }

    unsigned char keystream() {
        static int i = 0, j = 0;
        i = (i + 1) % 256;
        j = (j + S[i]) % 256;

        std::swap(S[i], S[j]);
        return S[(S[i] + S[j]) % 256];
    }

    std::vector<unsigned char> S;
    std::vector<unsigned char> K;
};

int main() {
    std::string key = "secret_key";
    std::string plaintext = "202111672313LanTian";
    
    RC4 rc4(key);

    // 加密
    std::string ciphertext = rc4.encryptDecrypt(plaintext);
    std::cout << "Ciphertext: ";
    for (unsigned char c : ciphertext) {
        std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)c;
    }
    std::cout << std::endl;

    // 解密（RC4 是对称的，加密和解密使用相同的方法）
    std::string decryptedtext = rc4.encryptDecrypt(ciphertext);
    std::cout << "Decrypted text: " << decryptedtext << std::endl;

    return 0;
}
